/************************************************************
 * Filename: Main.cpp
 * Purpose: Main entry point for game application.
 * Author: Jeremy Kings
 * Revision: 5 (15 December 2010)
 *
 * Copyright 2010, Digipen Institute of Technology
 ************************************************************/
#include "Precompiled.h"
#include "Main.h"

using namespace Engine;

const char windowTitle[] = "Engine"; // title displayed on application window
const int ClientWidth = 1024; const int ClientHeight = 768; // screen dimensions

// ---------------------------------------------------------------------------

void EnableMemoryLeakChecking(int breakAlloc=-1)
{
	//Set the leak checking flag
	int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
	tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF;
	_CrtSetDbgFlag(tmpDbgFlag);
	//If a valid break alloc provided set the breakAlloc
	if(breakAlloc!=-1) _CrtSetBreakAlloc( breakAlloc );
}

// ---------------------------------------------------------------------------

int WINAPI WinMain(HINSTANCE instanceH, HINSTANCE prevInstanceH, LPSTR command_line, int show)
{
	EnableMemoryLeakChecking();

	GameStateManager* manager = new GameStateManager(GS_Intro); // create the game state manager

	WindowsSystem* windows = new WindowsSystem(windowTitle, ClientWidth, ClientHeight);
	Graphics* graphics = new Graphics(windows->hWnd, ClientWidth, ClientHeight);

	// create systems and add to game state manager
	manager->AddSystem(windows);
	manager->AddSystem(new ObjectFactory());
	manager->AddSystem(new GameLogic(ClientWidth, ClientHeight));
	manager->AddSystem(new Physics());
	manager->AddSystem(new Audio());
	manager->AddSystem(graphics);

	windows->ActivateWindow(); // show the window

	manager->RunLoop(); // enter game loop

	delete manager;

	return 0;
}

// ---------------------------------------------------------------------------

//A basic error output function
bool SignalErrorHandler(const char * exp, const char * file, int line, const char * msg , ...)
{
	const int BufferSize = 1024;
	char FinalMessage[BufferSize];

	//Print out the file and line in visual studio format so the error can be
	//double clicked in the output window file(line) : error
	int offset = sprintf_s(FinalMessage,"%s(%d) : ", file , line );	
	if (msg != NULL)
	{	
		va_list args;
		va_start(args, msg);
		vsnprintf_s(FinalMessage + offset, BufferSize - offset, _TRUNCATE , msg, args);
		va_end(args);
	}
	else
	{
		strcpy_s(FinalMessage + offset, BufferSize - offset, "No Error Message");
	}

	//Print to visual studio output window
	OutputDebugString(FinalMessage);
	OutputDebugString("\n");

	//Display a message box to the user
	MessageBoxA(NULL, FinalMessage, "Error", 0);
	
	//Do not debug break
	return true;
}

// ---------------------------------------------------------------------------